(window as any)._AMapSecurityConfig = {
  securityJsCode: 'c7bed92083c4a4766621fd45d3a07eba',
};

const _getLocalAddress = () => {
  const AMap = (window as any).AMap;
  const mapObj = new AMap.Map('iCenter');
  return new Promise((resolve, reject) => {
    mapObj.plugin('AMap.Geolocation', () => {
      const geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, //是否使用高精度定位，默认:true
        GeoLocationFirst: true,
        timeout: 10000, //超过10秒后停止定位，默认：无穷大
        maximumAge: 0, //定位结果缓存0毫秒，默认：0
        convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
      });
      mapObj.addControl(geolocation);
      geolocation.getCurrentPosition();
      AMap.event.addListener(geolocation, 'complete', (res: { position: { lat: any; lng: any } }) => {
        const { lat, lng } = res.position;
        const geocoder = new AMap.Geocoder({
          radius: 1000, //范围，默认：500
        });
        console.log('获取经纬度---', [lng, lat]);
        geocoder.getAddress(
          [lng, lat],
          (
            status: string,
            result: { regeocode: { formattedAddress: any; addressComponent: { adcode: any; province: any; city: any; district: any } } },
          ) => {
            if (status === 'complete' && result.regeocode) {
              const address = result.regeocode.formattedAddress;
              console.log(address, result.regeocode);
              const { adcode, province, city, district } = result.regeocode.addressComponent;
              const addressList = [province, city, district];
              resolve({ addressList, adcode });
            } else {
              reject('根据经纬度查询地址失败');
              console.error('根据经纬度查询地址失败');
            }
          },
        );
      }); //返回定位信息
      AMap.event.addListener(geolocation, 'error', (err: any) => {
        reject('获取位置失败');
        console.log('获取位置失败', err);
      }); //返回定位出错信息
    });
  });
};
const getLocalAddress = () => {
  return new Promise<{addressList: string[], adcode: string}>((resolve, reject) => {
    if ((window as any).AMap && (window as any).AMap.Geocoder) {
      _getLocalAddress()
        .then((res) => resolve(res as any))
        .catch((err) => reject(err));
    } else {
      const scriptDom = (() => {
        const dom = document.querySelector('head #amap_sctipt_dom')
        if (dom) return dom as HTMLScriptElement
        const _scriptDom = document.createElement('script');
        _scriptDom.id = 'amap_sctipt_dom'
        _scriptDom.src = 'https://webapi.amap.com/maps?v=1.4.15&key=ed136946a8eb73746db3b7fc2705489a&plugin=AMap.Geocoder';
        return _scriptDom;
      })()
      scriptDom.onload = () => {
        _getLocalAddress()
          .then((res) => resolve(res as any))
          .catch((err) => reject(err));
      };
      scriptDom.onerror = () => {
        reject('插件加载失败');
      };
      document.querySelector('head')?.append(scriptDom);
    }
  });
};

export const useLocalAMap = () =>({
  getLocalAddress
})
